/**
 * @author   Ivan Andonov
 * @email:   ivan.andonov[at]gmail[dot]com
 *
 * @require  sjs 
 * @use      sjs.Ajax, sjs.Utils, sjs.Delegate, sjs.Form, json2
 * @optional sjs.Debug
 **/

(function() {

	sjs.create('sjs.AjaxForm', {
		
		// CONSTRUCTOR
		initialize : function(form, url, useJSON) {
			$log(this+' constructor form='+form+' url='+url+' useJSON='+useJSON);
			
			// PUBLIC VARS
			this.form = $element(form);
			this.url = url;
			this.ajax = new sjs.Ajax();
			this.useJSON = useJSON;
			
			// PUBLIC METHODS
			this.getProps = function() {
				//$log(this+'.getProps');
				var name, value, type;
				var props = {};
				var len = this.form.elements.length;
				for (var i = 0; i < len; i++) {
					name = this.form.elements[i].name;
					value = '';
					if (name && (name = this.classInstance().formatName(this.form.elements[i].name))) {
						switch (this.form.elements[i].nodeName.toLowerCase()) {
							case 'button':
								break;
							case 'input':
								type = this.form.elements[i].type;
								if (type == 'button' || type == 'submit') {
									break;
								} else if (type == 'radio') {
									value = new sjs.Form.RadioGroup(name).getIndex();
								}
							default:
								if (!value.length) {
									value = this.form.elements[i].value;
								}
								if (!props[name]) {
									props[name] = [];
								}
								props[name].push(value);
						}
					}
				}
				return props;
			};
			
			this.send = function(url, success, error, prop, useJSON) {
				$log(this+'.send url='+url+' prop='+prop+' useJSON='+useJSON);
				var props = {};
				if (prop) {
					if ((useJSON || this.useJSON) && window.JSON != null) {
						props[prop||'formData'] = JSON.stringify(this.getProps());
					} else {
						props[prop] = this.getProps();
					}
				}
				this.ajax.post(url || this.url, props, success, error);
			};
		}, 
		
		// PUBLIC STATIC METHODS
		formatName : function(name) {
			return name.replace(/\[\]/i, '');
		}
		
	});
	
})();